<template>
  <div>
    <FormPanel ref="from" :list="formList" :isSubmitBtn="false" :collapse="false" :labelWidth="190" />
    <FilterTable ref="table" :columns="columns" :defaultSelections="selectVin" :dataSource="tableList" :onRowSelectChange="selectChangeHandle" height="auto" :onColumnsChange="columns => (this.columns = columns)">
      <template slot="controls" slot-scope="props">
        <multiuse-button size="small" type="primary" :click="addHandle.bind(this, 1)" :disabled="isDisabled">审批通过</multiuse-button>
        <multiuse-button size="small" type="primary" :click="addHandle.bind(this, 2)" :disabled="isDisabled">取 消</multiuse-button>
        <!-- <el-button size="small" type="primary"  @click="addHandle(1)" :disabled="isDisabled">审核通过</el-button>
        <el-button  size="small" type="primary" @click="addHandle(2)" :disabled="isDisabled">取 消</el-button> -->
      </template>
    </FilterTable>

    <FormPanel ref="froms" :list="formLists" :isSubmitBtn="false" :collapse="false" labelWidth="110" @formChange="changeHandle" />
    <BreakSpace label="操作记录" />
    <FilterTable ref="table" :columns="columns1" :dataSource="tableLists" :datakey="'records'" height="auto" :isSelectColumn="false" :onColumnsChange="columns => (this.columns1 = columns)">
    </FilterTable>
    <BaseDialog :visible.sync="isDiscount" :title="'折扣详情'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <DiscountDetail :rowData="DiscountData" @close="Discountclose" />
    </BaseDialog>
    <div style="height:47px;"></div>
    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right'
      }"
    >
      <el-button @click="closeDrawer(1)">关 闭</el-button>
      <!-- <el-button @click="closeDrawer(2)" type="primary">审核驳回</el-button> -->
      <multiuse-button type="primary" :click="closeDrawer.bind(this, 2)">审核驳回</multiuse-button>
    </div>
  </div>
</template>
<script>
import { getLog } from '@/api/dealerSale/OrderManagement/OrderSubmission/index.js';
import { getList, getDetail, exportList, getAmount, postorderAudit, getNotPage } from '@/api/omSale/OrderManagement/PurchaseOrder/index.js';
import { dictionary } from '@/utils/dictMixin';
import DiscountDetail from './DiscountDetail';
import moment from 'moment';
export default {
  data() {
    this.saveData = null;
    return {
      formList: this.createdFrom(),
      formLists: this.createdFroms(),
      columns: this.createdTable(),
      columns1: this.createdTables(),
      tableList: [],
      tableLists: [],
      isaddCar: false,
      iscontract: false,
      isProject: false,
      isDiscount: false,
      DiscountData: {},
      isowner: false,
      seletctList: [],
      selectVin:[],
      isDisabled: true
    };
  },
  mixins: [dictionary],
  created() {
    this.getLog(this.rowData.orderId);
    this.getDetail(this.rowData);
  },
  props: ['rowData'],
  components: {
    DiscountDetail
  },
  methods: {
    createdFrom() {
      return [
        {
          type: 'BREAK_SPACE',
          label: '订单信息'
        },

        {
          type: 'INPUT',
          label: '订货单编号',
          fieldName: 'orderNo',
          placeholder: '请输入',
          disabled: true
        },
        {
          type: 'DATE',
          label: '订单年月',
          fieldName: 'orderYearMonth',
          disabled: true,
          placeholder: '请输入',
          dateType: 'month'
        },
        {
          type: 'SELECT',
          label: '订单状态',
          fieldName: 'orderStatus',
          disabled: true,
          placeholder: '请选择',
          itemList: this.createDictList('6043'),
          initialValue: 60431001
        },
        {
          type: 'SELECT',
          label: '订单类型',
          fieldName: 'orderType',
          placeholder: '请选择',
          disabled: true,
          itemList: this.createDictList('6006')
        },
        {
          type: 'SELECT',
          label: '订单细分类型',
          fieldName: 'orderDetailType',
          placeholder: '请选择',
          itemList: [],
          disabled: true
        },
        {
          type: 'SELECT',
          label: '运输方式',
          fieldName: 'transportType',
          placeholder: '请选择',
          disabled: true,
          itemList: this.createDictList('6004')
        },
        {
          type: 'SELECT',
          label: '是否使用返利',
          fieldName: 'isRebate',
          placeholder: '请选择',
          disabled: true,
          itemList: this.createDictList('1004'),
          initialValue: 10041001
        },
        {
          type: 'INPUT',
          precision: 2,
          label: '资金总余额(油)',
          fieldName: 'totalFuelAmount',
          placeholder: '请选择',
          disabled: true
        },
        {
          type: 'INPUT',
          precision: 2,
          label: '资金总余额(电)',
          fieldName: 'totalEnergyAmount',
          placeholder: '请选择',
          disabled: true
        },
        {
          type: 'INPUT',
          precision:2,
          label: '单车返利余额(电)',
          fieldName: 'singleRebateEnergyAmount',
          placeholder: '请选择',
          disabled: true
        },

        {
          type: 'INPUT_NUMBER',
          precision:2,
          initialValue:0.00,
          label: '建店补贴直接带出池余额(电)',
          fieldName: 'buildRebateEnergyAmountStart',
          placeholder: '请选择',
          disabled: true
        },
        {
          type: 'INPUT_NUMBER',
          precision:2,
          initialValue:0.00,
          label: '建店补贴单车带出池余额(电)',
          fieldName: 'buildRebateEnergyAmountEnd',
          placeholder: '请选择',
          disabled: true
        },
        {
          type: 'INPUT',
          precision:2,
          label: '单车返利余额(油)',
          fieldName: 'singleRebateFuelAmount',
          placeholder: '请选择',
          disabled: true
        },
        {
          type: 'INPUT_NUMBER',
          precision:2,
          initialValue:0.00,
          label: '建店补贴直接带出池余额(油)',
          fieldName: 'buildRebateFuelAmountStart',
          placeholder: '请选择',
          disabled: true
        },
        {
          type: 'INPUT_NUMBER',
          label: '建店补贴单车带出池余额(油)',
          fieldName: 'buildRebateFuelAmountEnd',
          placeholder: '请选择',
          precision:2,
          initialValue:0.00,
          disabled: true
        },
        {
          type: 'INPUT_NUMBER',
          precision:2,
          label: '单车返利使用金额(电)',
          fieldName: 'singleRebateEnergyTotalAmount',
          placeholder: '请选择',
          initialValue:0.00,
          disabled: true
        },
        {
          type: 'INPUT_NUMBER',
          precision:2,
          label: '建店补贴首使用金额(电)',
          fieldName: 'buildRebateEnergyTotalAmountStart',
          placeholder: '请选择',
          initialValue:0.00,
          disabled: true
        },
        {
          type: 'INPUT_NUMBER',
          precision:2,
          label: '建店补贴尾使用金额(电)',
          fieldName: 'buildRebateEnergyTotalAmount',
          placeholder: '请选择',
          initialValue:0.00,
          disabled: true
        },
        {
          type: 'INPUT_NUMBER',
          precision:2,
          label: '单车返利使用金额(油)',
          fieldName: 'singleRebateFuelTotalAmount',
          placeholder: '请选择',
          initialValue:0.00,
          disabled: true
        },
        {
          type: 'INPUT_NUMBER',
          precision:2,
          label: '建店补贴首使用金额(油)',
          fieldName: 'buildRebateFuelTotalAmountStart',
          placeholder: '请选择',
          initialValue:0.00,
          disabled: true
        },
        {
          type: 'INPUT_NUMBER',
          precision:2,
          label: '建店补贴尾使用金额(油)',
          fieldName: 'buildRebateFuelTotalAmount',
          placeholder: '请选择',
          initialValue:0.00,
          disabled: true
        },
        {
          type: 'INPUT_NUMBER',
          precision: 2,
          label: '实付总金额',
          fieldName: 'realPayTotalAmount',
          disabled: true
        },

        {
          type: 'BREAK_SPACE',
          label: '车辆信息'
        }
      ];
    },
    createdFroms() {
      return [
        {
          type: 'TEXT_AREA',
          label: '审核意见',
          fieldName: 'auditOpinion',
          placeholder: '请输入',
          selfCols: 2
        }
      ];
    },
    createdTable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '收车地址',
          dataIndex: 'detaildAddress',
          sorter: true,
          filter: true,
          filterType: 'input'
        },

        {
          title: '产品代码',
          dataIndex: 'productCode',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '产品名称',
          dataIndex: 'productName',
          align: 'center',
          width: 400,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '车型名称',
          dataIndex: 'modelName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '内饰',
          dataIndex: 'trimName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '外饰',
          dataIndex: 'colorName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '提报数量',
          dataIndex: 'orderNum',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '可用资源',
          dataIndex: 'avilableCount',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: p => {
            return <span>{p.row.avilableCount ? p.row.avilableCount : 0}</span>;
          }
        },
        {
          title: '审核数量',
          dataIndex: 'auditNum',
          sorter: true,
          filter: true,
          filterType: 'input',
          editable: true,
          editType: 'number',
          defaultEditable: true,
          summation: true
        },
        {
          title: '已审',
          dataIndex: 'checkNum',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '已取消',
          dataIndex: 'cancelNum',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '状态',
          dataIndex: 'orderDetailStatus',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: [
            { text: '待审核', value: 60431003 },
            { text: '部分审核', value: 60431004 }
          ],
          render: p => {
            return <span>{this.createDictText(p.row.orderDetailStatus, '6043')}</span>;
          }
        },
        {
          title: '市场指导价（补贴前）',
          dataIndex: 'singleAmount',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '国补金额',
          dataIndex: 'subsidyAmount',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '市场指导价（补贴后）',
          dataIndex: 'beforeSingleAmount',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '折扣总金额',
          dataIndex: 'discountTotalAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          summation: true,
          render: p => {
            return (
              <span class="discount" onClick={() => this.getDiscount(p.row)}>
                {p.row.discountTotalAmount}
              </span>
            );
          }
        },
        {
          title: '单车返利总金额',
          dataIndex: 'singleRebateTotalAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          summation: true
        },
        {
          title: '建店返利类型',
          dataIndex: 'buildRebateType',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          editable:false,
          filterItems: this.createDictList('6036').filter(x=>x.value!==60361001),
          editType: 'select',
          editItems: this.createDictList('6036').filter(x=>x.value!==60361001),
        },
        {
          title: '建店返利总金额',
          dataIndex: 'buildRebateTotalAmountLocalShow',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '单车返利金额',
          dataIndex: 'singleRebateAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          precision: 2,
          hidden: true
        },
        {
          title: '建店返利金额',
          dataIndex: 'buildRebateAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          precision: 2,
          hidden: true
        },
        {
          title: '折后单价',
          dataIndex: 'afterDiscountAmount',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '折前总金额',
          dataIndex: 'totalAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          summation: true
        },
        {
          title: '折后总金额',
          dataIndex: 'afterTotalAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          summation: true
        },
        {
          title: '备注',
          dataIndex: 'remark',
          sorter: true,
          filter: true,
          filterType: 'input'
        }
      ];
    },
    createdTables() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          fixed: 'left',
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '单据执行前状态',
          dataIndex: 'beforeOrderStatus',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('6043'),
          render: p => {
            return <span>{this.createDictText(p.row.beforeOrderStatus, '6043')}</span>;
          }
        },
        {
          title: '单独执行后状态',
          dataIndex: 'afterOrderStatus',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('6043'),
          render: p => {
            return <span>{this.createDictText(p.row.afterOrderStatus, '6043')}</span>;
          }
        },
        {
          title: '操作人员',
          dataIndex: 'createdName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '操作时间',
          dataIndex: 'createdAt',
          sorter: true,
          filter: true,
          filterType: 'date-range'
        },
        {
          title: '操作类型',
          dataIndex: 'operationType',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: p => {
            return <span>{p.row.operationType}</span>;
          }
        },
        {
          title: '审批意见',
          dataIndex: 'auditOpinion',
          sorter: true,
          filter: true,
          filterType: 'input'
        }
      ];
    },
    // 获取详情
    async getDetail(data) {
      let res = await getDetail({ orderId: data.orderId, getType: 'avilable' });
      for (let i in res.data) {
        this.formList.map(x => {
          if (x.fieldName == 'buildRebateEnergyAmount') {
          } else if (x.fieldName == 'buildRebateFuelAmount') {
          } else if (x.fieldName == 'singleRebateEnergyAmount') {
          } else if (x.fieldName == 'singleRebateFuelAmount') {
          } else if (x.fieldName == 'totalEnergyAmount') {
          } else if (x.fieldName == 'totalFuelAmount') {
          } else if (x.fieldName == 'buildRebateEnergyAmountEnd') {
          } else if (x.fieldName == 'buildRebateEnergyAmountStart') {
          } else if (x.fieldName == 'buildRebateFuelAmountEnd') {
          } else if (x.fieldName == 'buildRebateFuelAmountStart') {
          } else if (i == x.fieldName) {
            x.initialValue = res.data[i];
          }
        });
      }

      // this.getNotPage(res.data.orderType)
      res.data.detailDTOList.map(x => {
        x.addressList = x.addressList.map(x => ({ text: x.detaildAddress, value: x.addressId, addressProperty: x.addressProperty, isnew: false }));
        x.auditNum = x.orderNum - x.checkNum - x.cancelNum;
        x.buildRebateTotalAmountLocalShow=x.buildRebateTotalAmount+x.buildRebateTotalAmountStart
      });
      this.getNotPage(res.data.orderType);
      this.getAmountDetail(res.data.dealerCode);
      this.tableList = res.data.detailDTOList || [];
      if(this.tableList){
        this.selectVin = [this.tableList[0]];
      }
    },
    async getAmountDetail(code) {
      let res = await getAmount({ dealerCode: code });

      for (let i in res.data) {
        this.formList.map(x => {
          if (x.fieldName == i) {
            x.initialValue = res.data[i];
          }
        });
      }
      this.json = res.data;
    },
    async addHandle(type) {
      let arr = [];
      let is = false;
      let Reg = /^[1-9]\d*$/;
      this.seletctList.map(x => {
        if (!x.auditNum || !Reg.test(x.auditNum)) {
          is = true;
        }
        if (x.auditNum > x.orderNum) {
          is = true;
        }
      });
      let str = this.formLists.find(x => x.fieldName == 'auditOpinion').initialValue;
      if (!is) {
        if (type == 1) {
          let json = {
            orderId: this.rowData.orderId,
            auditType: 'pass',
            dealerCode: this.rowData.dealerCode,
            detailDTOList: this.seletctList,
            auditOpinion: str
          };

          let res = await postorderAudit(json);
          if (res.resultCode == 200) {
            this.$notify({
              title: '成功',
              message: '审核通过成功',
              type: 'success'
            });
            if (!res.data.detailDTOList) {
              this.$emit('close');
            } else {
              this.getAmountDetail(this.rowData.dealerCode);
              for (let i in res.data) {
                this.formList.map(x => {
                  if (x.fieldName == 'buildRebateEnergyAmount') {
                  } else if (x.fieldName == 'buildRebateFuelAmount') {
                  } else if (x.fieldName == 'singleRebateEnergyAmount') {
                  } else if (x.fieldName == 'singleRebateFuelAmount') {
                  } else if (x.fieldName == 'totalEnergyAmount') {
                  } else if (x.fieldName == 'totalFuelAmount') {
                  } else if (x.fieldName == 'buildRebateEnergyAmountEnd') {
                  } else if (x.fieldName == 'buildRebateEnergyAmountStart') {
                  } else if (x.fieldName == 'buildRebateFuelAmountEnd') {
                  } else if (x.fieldName == 'buildRebateFuelAmountStart') {
                  } else if (i == x.fieldName) {
                    x.initialValue = res.data[i];
                  }
                });
              }
              this.isDisabled = true;
              this.formLists.find(x => x.fieldName == 'auditOpinion').initialValue = '';
              res.data.detailDTOList.map(x => {
                x.addressList = x.addressList.map(x => ({ text: x.detaildAddress, value: x.addressId, addressProperty: x.addressProperty, isnew: false }));
                x.auditNum = x.orderNum - x.checkNum - x.cancelNum;
              });
              this.tableList = res.data.detailDTOList;
            }

            console.log(res);
          }
        } else {
          let json = {
            orderId: this.rowData.orderId,
            auditType: 'cancel',
            dealerCode: this.rowData.dealerCode,
            detailDTOList: this.seletctList,
            auditOpinion: str
          };
          let res = await postorderAudit(json);
          if (res.resultCode == 200) {
            this.$notify({
              title: '成功',
              message: '取消成功',
              type: 'success'
            });
            if (!res.data.detailDTOList) {
              this.$emit('close');
            } else {
              this.getAmountDetail(this.rowData.dealerCode);
              for (let i in res.data) {
                this.formList.map(x => {
                  if (x.fieldName == 'totalAmount') {
                  } else if (x.fieldName == 'singleRebateAmount') {
                  } else if (x.fieldName == 'buildRebateAmount') {
                  } else if (x.fieldName == 'buildRebateEnergyAmountEnd') {
                  } else if (x.fieldName == 'buildRebateEnergyAmountStart') {
                  } else if (x.fieldName == 'buildRebateFuelAmountEnd') {
                  } else if (x.fieldName == 'buildRebateFuelAmountStart') {
                  } else if (i == x.fieldName) {
                    x.initialValue = res.data[i];
                  }
                });
              }
              this.isDisabled = true;
              this.formLists.find(x => x.fieldName == 'auditOpinion').initialValue = '';
              res.data.detailDTOList.map(x => {
                x.addressList = x.addressList.map(x => ({ text: x.detaildAddress, value: x.addressId, addressProperty: x.addressProperty, isnew: false }));
                x.auditNum = x.orderNum - x.checkNum - x.cancelNum;
              });
              this.tableList = res.data.detailDTOList;
            }
          }
        }
      } else {
        this.$notify({
          title: '警告',
          message: '审核数量未填或不符合规则',
          type: 'warning'
        });
        return;
      }
    },
    changeHandle(val) {
      this.saveData = val;
    },
    selectChangeHandle(val) {
      if (val.length > 0) {
        this.seletctList = val;
        this.isDisabled = false;
      } else {
        this.seletctList = [];
        this.isDisabled = true;
      }
    },
    getDiscount(data) {
      this.DiscountData = data;
      this.isDiscount = true;
    },
    // 加载折扣信息
    async getNotPage(orderType) {
      let list = await getNotPage({ orderType: orderType });
      this.formList.map(x => {
        if (x.fieldName == 'orderDetailType') {
          x.itemList = list.data.map(x => ({ text: x.subName, value: x.subId }));
        }
      });
    },
    async getLog(id) {
      let res = await getLog({ orderId: id });
      console.log(res, '2');
      this.tableLists = res.data || [];
    },
    Discountclose() {
      this.isDiscount = false;
    },
    async closeDrawer(type) {
      if (type == 1) {
        this.$emit('close');
      } else {
        let is = false;
        this.tableList.map(x => {
          if (x.checkNum > 0 || x.cancelNum > 0) {
            is = true;
          }
        });
        if (!is) {
          let str = this.formLists.find(x => x.fieldName == 'auditOpinion').initialValue;
          if (str) {
            let json = {};
            json.dealerCode = this.rowData.dealerCode;
            json.orderId = this.rowData.orderId;
            json.auditType = 'rejected';
            json.auditOpinion = str;
            json.detailDTOList = this.tableList;
            let res = await postorderAudit(json);
            if (res.resultCode == 200) {
              this.$notify({
                title: '成功',
                message: '驳回成功',
                type: 'success'
              });
              this.$emit('close', json);
            }
          } else {
            this.$notify({
              title: '警告',
              message: '驳回请填写审核意见',
              type: 'warning'
            });
          }
        } else {
          this.$notify({
            title: '警告',
            message: '数据已进行操作，不能驳回',
            type: 'warning'
          });
          return;
        }
      }
    }
  }
};
</script>
<style lang="less">
.discount {
  text-decoration: underline;
  color: #d1291a;
  cursor: pointer;
}
</style>
